package com.lk.template.config;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * MVC
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {


  @Resource
  private AuthInterceptor authInterceptor;

  /**
   * 拦截器
   */
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    // 放行路径
    List<String> excludePath = List.of(
      "/doc.html",
      "/swagger-ui.html",
      "/swagger-ui/**",
      "/swagger-resources/**",
      "/v3/api-docs/**",
      "/webjars/**",
      "/resources/**",
      "/static/**",
      "/error",
      "/favicon.ico"
    );
    registry.addInterceptor(authInterceptor).addPathPatterns(excludePath).order(1);
  }

  /**
   * 静态资源拦截
   */
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    // 放开knife4j的html拦截
    registry.addResourceHandler("/doc.html")
      .addResourceLocations("classpath:/META-INF/resources/");
    // 放开knife4j的css和js拦截
    registry.addResourceHandler("/webjars/**")
      .addResourceLocations("classpath:/META-INF/resources/webjars/");
    //放开knife4j的图片拦截
    registry.addResourceHandler("/img/**")
      .addResourceLocations("classpath:/META-INF/resources/img/");
    // 放开静态资源
    registry.addResourceHandler("/file/**")
      .addResourceLocations("classpath:META-INF/resources/static/file/");
  }

  /**
   * 跨域
   */
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    //允许跨域的路径
    registry.addMapping("/**")
      //请求头
      .allowedHeaders("*")
      //响应头
      .exposedHeaders("*")
      //证书
      .allowCredentials(true)
      //域名
      //.allowedOrigins()
      .allowedOriginPatterns("*")
      //方法
      .allowedMethods("*")
      //时间
      .maxAge(36000);
  }
}
